use clap::Parser;
use anyhow::Result;
use std::process;
use crate::config::Config;
use crate::api::GitCodeAPI;

#[derive(Parser)]
#[clap(name = "gitcode-cli-rust", version = "1.0", author = "Your Name")]
pub struct Cli {
    #[clap(subcommand)]
    command: Command,
}

#[derive(clap::Subcommand)]
enum Command {
    /// 登录到 GitCode
    Login {
        /// 访问令牌
        #[clap(short, long)]
        token: String,
    },
    /// 退出登录
    Logout,
    /// 上传文件到仓库
    Upload {
        /// 仓库 ID
        #[clap(short, long)]
        repo: String,
        /// 文件路径
        #[clap(short, long)]
        file: String,
    },
    /// 下载仓库
    Download {
        /// 仓库 ID
        #[clap(short, long)]
        repo: String,
        /// 目标目录
        #[clap(short, long)]
        dir: Option<String>,
    },
    /// 显示当前配置
    ConfigShow,
}

impl Cli {
    pub async fn run(self) -> Result<()> {
        // 加载配置
        let mut config = Config::load()?;
        let api = GitCodeAPI::new(config.clone());
        
        match self.command {
            Command::Login { ref token } => {
                self.handle_login(token.clone(), &api, &mut config).await?;
            }
            Command::Logout => {
                self.handle_logout(&api, &mut config).await?;
            }
            Command::Upload { ref repo, ref file } => {
                self.handle_upload(repo.clone(), file.clone(), &api).await?;
            }
            Command::Download { ref repo, ref dir } => {
                self.handle_download(repo.clone(), dir.clone(), &api).await?;
            }
            Command::ConfigShow => {
                self.handle_config_show(&config)?;
            }
        }
        
        Ok(())
    }
    
    async fn handle_login(&self, token: String, api: &GitCodeAPI, config: &mut Config) -> Result<()> {
        println!("正在登录...");
        let response = api.login(&token).await?;
        
        if response.success {
            config.set_token(token);
            config.save()?;
            println!("{}", response.message);
        } else {
            eprintln!("登录失败: {}", response.message);
            process::exit(1);
        }
        
        Ok(())
    }
    
    async fn handle_logout(&self, api: &GitCodeAPI, config: &mut Config) -> Result<()> {
        if !api.is_logged_in() {
            println!("当前未登录");
            return Ok(());
        }
        
        config.clear_token();
        config.save()?;
        println!("已退出登录");
        Ok(())
    }
    
    async fn handle_upload(&self, repo_id: String, file_path: String, api: &GitCodeAPI) -> Result<()> {
        if !api.is_logged_in() {
            eprintln!("请先登录");
            process::exit(1);
        }
        
        api.upload_file(&repo_id, &file_path).await?;
        println!("文件上传成功");
        Ok(())
    }
    
    async fn handle_download(&self, repo_id: String, directory: Option<String>, api: &GitCodeAPI) -> Result<()> {
        if !api.is_logged_in() {
            eprintln!("请先登录");
            process::exit(1);
        }
        
        // 如果没有提供目录，则使用默认目录
        let dir = directory.unwrap_or_else(|| {
            format!("./{}", repo_id.split('/').next_back().unwrap_or("repo"))
        });
        
        api.download_repository(&repo_id, &dir).await?;
        println!("仓库下载成功到: {}", dir);
        Ok(())
    }
    
    fn handle_config_show(&self, config: &Config) -> Result<()> {
        println!("当前配置:");
        if let Some(token) = config.get_token() {
            println!("  Token: {}", token);
        } else {
            println!("  Token: 未设置");
        }
        Ok(())
    }
}